import axios from 'axios'
import { ElMessage } from 'element-plus'
import { API_CONFIG } from './config'
import { tokenManager } from './auth/tokenManager'
import { authApi } from './auth/authApi'

// 创建axios实例
const api = axios.create({
  baseURL: API_CONFIG.baseURL,
  timeout: API_CONFIG.timeout
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const accessToken = tokenManager.getAccessToken()
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  async error => {
    const originalRequest = error.config

    // 如果是401错误且不是刷新token的请求，尝试刷新token
    if (error.response?.status === 401 && !originalRequest._retry && originalRequest.url !== API_CONFIG.authEndpoints.refresh) {
      originalRequest._retry = true
      
      try {
        const newAccessToken = await authApi.refreshToken()
        originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`
        return api(originalRequest)
      } catch (refreshError) {
        return Promise.reject(refreshError)
      }
    }

    ElMessage.error(error.response?.data?.message || '请求失败')
    return Promise.reject(error)
  }
)

export default api 